package com.example.rule_engine.config;

import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @Description DroolsConfig
 * @Author lihw
 * @Date 2023/12/4 14:40
 */
@Slf4j
@Configuration
public class DroolsConfig {
    /**
     * 定义规则路径
     */
    private static final String RULES_PATH = "classpath*:/rules/*.drl";

    @Bean
    public KieContainer kieContainer() throws IOException {
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();

        // 加载所有规则文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(RULES_PATH);
        for (int i = 0; i < resources.length; i++) {
            org.kie.api.io.Resource resource = ResourceFactory.newFileResource(resources[i].getFile());
            kieFileSystem.write(resource);
        }
        // 加载一个规则文件
        // kieFileSystem.write(ResourceFactory.newClassPathResource("rules/rules.drl"));

        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        kb.buildAll();
        KieModule kieModule = kb.getKieModule();
        return kieServices.newKieContainer(kieModule.getReleaseId());
    }




}
